<?php

declare(strict_types=1);

namespace App\Chat\Service;

use App\CustHub\Mapper\ChCustomerServiceMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChContact;
use App\CustHub\Model\ChCorpTag;
use App\CustHub\Model\ChCustomerService;
use App\CustHub\Model\ChRobot;
use App\CustHub\Model\ChRoom;
use App\CustHub\Model\ChRoomMember;
use App\CustHub\Model\ChSmartTag;
use App\CustHub\Service\ChContactService;
use App\CustHub\Service\ChContactTaskCenterService;
use App\CustHub\Service\ChCorpTagService;
use App\CustHub\Service\ChSmartTagService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;

class TalkContactService extends AbstractService
{
    #[Inject]
    protected ChRobotMapper $robotMapper;

    #[Inject]
    protected ChCorpTagService $corpTagService;

    #[Inject]
    protected ChCustomerServiceMapper $customerServiceMapper;

    #[Inject]
    protected ChSmartTagService $smartTagService;

    #[Inject]
    protected ChContactService $contactService;

    public function getInfo(array $data)
    {
        $userId = $data['user_id'];
        $robotId = $data['robot_id'];

        $contactInfo = ChContact::query()
            ->select(['id','main_uid','nickname','avatar','user_id','corp_name','corp_short_name','remark','desc','mobile_list','add_customer_time'])
            ->where('robot_id',$robotId)
            ->where('user_id',$userId)
            ->first();
        if(empty($contactInfo)){
            throw new NormalStatusException('客户不存在');
        }

        $contactInfo['add_time'] = empty($contactInfo->add_customer_time) ? '' : datetime($contactInfo->add_customer_time);

        $corpTagIds = $contactInfo->corpTags()->pluck('id')->toArray();
        $smartTagIds = $contactInfo->smartTags()->pluck('id')->toArray();
        $mobileList = $contactInfo->mobileList()->pluck('mobile')->toArray();
        $contactInfo->mobile_list = $mobileList;

        $corpTagList = ChCorpTag::query()
            ->select(['id','name','group_id','label_type'])
            ->whereIn('id',$corpTagIds)
            ->where('is_deleted',0)
            ->get();


        $wxWorkTagList = $corpTagList->filter(function ($item){
            return $item['label_type'] == 1;
        });

        $wxWorkTagIds = $wxWorkTagList->pluck('id')->toArray();
        $wxWorkTagList =  $wxWorkTagList->groupBy('group_id');
        $wxWorkGroupIds = $wxWorkTagList->keys();
        $wxWorkParentTagList = ChCorpTag::query()
            ->select(['id','name'])
            ->whereIn('id',$wxWorkGroupIds)
            ->where('is_deleted',0)
            ->get()->toArray();

        foreach ($wxWorkParentTagList as $k=>$item){
            $wxWorkParentTagList[$k]['sub'] = $wxWorkTagList[$item['id']];
        }


        $wxTagList = $corpTagList->filter(function ($item){
            return $item['label_type'] == 2;
        });

        $wxTagIds = $wxTagList->pluck('id')->toArray();
        $wxTagList = $wxTagList->groupBy('group_id');
        $wxGroupIds = $wxTagList->keys();
        $wxParentTagList = ChCorpTag::query()
            ->select(['id','name'])
            ->whereIn('id',$wxGroupIds)
            ->where('is_deleted',0)
            ->get()->toArray();

        foreach ($wxParentTagList as $k=>$item){
            $wxParentTagList[$k]['sub'] = $wxTagList[$item['id']];
        }

        //智能标签
        $smartTagList = ChSmartTag::query()
            ->select(['id','name','parent_id'])
            ->whereIn('id',$smartTagIds)
            ->where('parent_id','<>',0)
            ->get()->groupBy('parent_id');

        $parentIds = $smartTagList->keys();

        $smartParentTagList = ChSmartTag::query()
            ->select(['id','name'])
            ->whereIn('id',$parentIds)
            ->get()->toArray();

        foreach ($smartParentTagList as $k=>$item){
            $smartParentTagList[$k]['sub'] = $smartTagList[$item['id']];
        }

        $contactInfo['wx_work_tag_list'] = $wxWorkParentTagList;
        $contactInfo['wx_work_tag_ids'] = $wxWorkTagIds;
        $contactInfo['wx_tag_list'] = $wxParentTagList;
        $contactInfo['wx_tag_ids'] = $wxTagIds;
        $contactInfo['smart_tag_list'] = $smartParentTagList;
        $contactInfo['smart_tag_ids'] = $smartTagIds;

        //所在群聊
        $roomList = Db::table('ch_room as r')
            ->selectRaw('r.id,r.room_name,r.room_avatar_url,r.room_member_count')
            ->join('ch_room_member as rm', 'r.room_wxid', '=', 'rm.room_wxid')
            ->where('r.main_uid',$contactInfo->main_uid)
            ->where('rm.user_id',$contactInfo->user_id)
            ->groupBy('r.id')
            ->get();
        $roomCount = $roomList->count();
        $contactInfo['room_list'] = $roomList;
        $contactInfo['room_count'] = $roomCount;

        //获取所有归属机器人
        $robotList = Db::table('ch_contact as c')
            ->selectRaw('r.id,r.nickname,r.avatar,r.corp_name,r.login_status')
            ->join('ch_robot as r','c.robot_id','=','r.id')
            ->where('c.main_uid',$contactInfo->main_uid)
            ->where('c.user_id',$contactInfo->user_id)
            ->groupBy('c.robot_id')
            ->get();

        $robotCount = $robotList->count();
        $contactInfo['robot_list'] = $robotList;
        $contactInfo['robot_count'] = $robotCount;


        return $contactInfo;
    }


    public function getWxWorkTagList(array $params): array
    {
        return $this->corpTagService->corpTagList($params);
    }

    public function getWxTagList(array $params): array
    {
        return $this->corpTagService->personalTagList($params);
    }

    public function getSmartTagList(array $params)
    {
        $csInfo = $this->customerServiceMapper->findById($params['uid']);

        $list = $this->smartTagService->selectList(['uid' => $csInfo->uid]);
        return $list;
    }

    public function setWxWorkTag(array $data)
    {
        $id = ChContact::query()
            ->where('robot_id',$data['robot_id'])
            ->where('user_id',$data['user_id'])
            ->value('id');
        if(empty($id)){
            throw new NormalStatusException('请选择客户');
        }

        return $this->contactService->commonSetCorpTag($id,json_decode($data['tag_ids'],true),1);
    }

    public function setWxTag(array $data)
    {
        $id = ChContact::query()
            ->where('robot_id',$data['robot_id'])
            ->where('user_id',$data['user_id'])
            ->value('id');
        if(empty($id)){
            throw new NormalStatusException('请选择客户');
        }

        return $this->contactService->commonSetCorpTag($id,json_decode($data['tag_ids'],true),2);
    }

    public function setSmartTag(array $data): bool
    {
        $contact = ChContact::query()
            ->where('robot_id',$data['robot_id'])
            ->where('user_id',$data['user_id'])
            ->first();
        if(empty($contact)){
            throw new NormalStatusException('请选择客户');
        }
        $smartTagsIds = json_decode($data['tag_ids'], true);
        $contact->smartTags()->sync($smartTagsIds);

        $existTagIds = $contact->smartTags()->pluck('id')->toArray();
        $removeTagIds = array_diff($existTagIds, $smartTagsIds);
        if(!empty($removeTagIds)){
            $contact->smartTags()->detach($removeTagIds);
        }

        container()->get(ChContactTaskCenterService::class)->updateSmartTagContactCnt([$contact->id], $smartTagsIds, $removeTagIds);
        return true;
    }

    public function setRemark(array $data): bool
    {
        $id = ChContact::query()
            ->where('robot_id',$data['robot_id'])
            ->where('user_id',$data['user_id'])
            ->value('id');
        if(empty($id)){
            throw new NormalStatusException('请选择客户');
        }

        return $this->contactService->editRemark(['id'=> $id,'remark'=>$data['remark']]);
    }

    public function setDesc(array $data): bool
    {
        $id = ChContact::query()
            ->where('robot_id',$data['robot_id'])
            ->where('user_id',$data['user_id'])
            ->value('id');
        if(empty($id)){
            throw new NormalStatusException('请选择客户');
        }

        return $this->contactService->editDesc(['id'=> $id,'desc'=>$data['desc']]);
    }


    public function setMobile(array $data): bool
    {
        $id = ChContact::query()
            ->where('robot_id',$data['robot_id'])
            ->where('user_id',$data['user_id'])
            ->value('id');
        if(empty($id)){
            throw new NormalStatusException('请选择客户');
        }

        return $this->contactService->editMobile(['id'=> $id,'mobile'=>$data['mobile']]);
    }
}